package logic

import (
	"context"
	"time"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateUserLogic {
	return &BackendUpdateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendUpdateUserLogic) BackendUpdateUser(in *backend.UpdateUserRequest) (*backend.UpdateUserResponse, error) {
	if in.Id == 0 {
		return nil, errorx.Status(errorx.ERROR_USER_ID_REQUIRED, "")
	}

	var pageSize int64 = 2
	userList, _, err := l.svcCtx.BackendUser.GetList(l.ctx, model.M{
		model.BackendUserColumns.Username: in.Username,
		"pageSize":                        pageSize,
		"select":                          ",",
	}, -1)
	if err != nil {
		return nil, err
	}
	count := len(userList)
	if count > 1 {
		return nil, errorx.Status(errorx.ERROR_USERNAME_EXISTS, "")
	}
	if count == 1 && userList[0].ID != uint64(in.Id) {
		return nil, errorx.Status(errorx.ERROR_USERNAME_EXISTS, "")
	}

	var user model.BackendUser
	user.ID = uint64(in.Id)
	user.Username = in.Username
	user.Nickname = in.Nickname
	user.Name = in.Name
	user.Email = in.Email
	user.Mobile = in.Mobile
	user.Status = uint16(in.Status)
	user.DelStatus = uint16(in.Status)
	user.LastUpdatedBy = uint64(in.UpdatedBy)
	user.UpdatedAt = time.Now()

	_, err = l.svcCtx.BackendUser.Update(l.ctx, &user)
	if err != nil {
		return nil, err
	}

	return &backend.UpdateUserResponse{}, nil
}
